package com.menker.app.webview;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;

import com.menker.app.Constants;
import com.menker.app.R;
import com.menker.app.common.BaseWebViewToolbarActivity;
import com.menker.app.common.ToolbarOwner;
import com.menker.app.di.Injector;
import com.menker.app.ui.main.MainActivity_;
import com.menker.app.util.DialogUtils;
import com.menker.app.util.TaobaoUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class CustomWebChromeClient extends WebChromeClient {
    private Activity mActivity;
    private ToolbarOwner.IToolbar mToolbar;

    public CustomWebChromeClient(Activity activity, ToolbarOwner.IToolbar toolbar) {
        mActivity = activity;
        mToolbar = toolbar;
    }

    /**
     * 根据页面的title来选择显示titleBar的图片内容
     */
    @Override
    public void onReceivedTitle(WebView view, String title) {
        if (!TaobaoUtils.isItemDetailsLink(view.getUrl()) && !TextUtils.isEmpty(title) && !title.contains("http")) {
            if (mToolbar != null) {
                mToolbar.setToolbarTitle(title);
            }
        }
//        int resId = 0;
//
//        // 不用switch语句的原因: JDK6不支持字符串,且不支持Enum中文
//        if (title.equals("登录")) {
//            resId = R.drawable.pic_title_login;
//        } else {
//            resId = R.drawable.img_title_main;
//        }
//
//        if (mIvTitle != null) {
//            mIvTitle.setBackgroundResource(resId);
//        }

        super.onReceivedTitle(view, title);
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
    }

    /**
     * 覆盖默认的window.alert展示界面，避免title里显示网址地址
     */
    @Override
    public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle(R.string.app_name)
                .setMessage(message)
                // 不需要绑定按键事件
                .setPositiveButton("确定", null)
                //屏蔽keycode等于84(search)之类的按键
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        return true;
                    }
                })
                // 禁止响应按back键的事件
                .setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
        // 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容
        result.confirm();
        return true;
    }

    /**
     * 覆盖默认的window.confirm展示界面，避免title里显示网址地址
     */
    @Override
    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle(R.string.app_name)
                .setMessage(message)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                })
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                })
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        result.cancel();
                    }
                })
                // 屏蔽keycode等于84(search)之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode,
                                         KeyEvent event) {
                        return true;
                    }
                });
        //禁止响应按back键的事件
//        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
        return true;
    }

    /**
     * 覆盖默认的window.prompt展示界面，避免title里显示网址地址
     */
    @Override
    public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
        final EditText et = new EditText(view.getContext());
        et.setSingleLine();
        et.setText(defaultValue);

        final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle(R.string.app_name)
                .setMessage(message)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm(et.getText().toString());
                    }
                })
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                })
                // 屏蔽keycode等于84(search)之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode,
                                         KeyEvent event) {
                        return true;
                    }
                });
        // 禁止响应按back键的事件
//        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
        return true;
    }


    // For Android < 3.0
//    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//        openFileChooser(uploadMsg, "");
//    }

    // For Android >= 3.0
//    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
//        if (uploadMsg == null) return;
//
//        if (mActivity instanceof BaseWebViewToolbarActivity) {
//            ((BaseWebViewToolbarActivity) mActivity).setUploadMessage(uploadMsg);
//        } else if (mActivity instanceof MainActivity_) {
//            ((MainActivity_) mActivity).setUploadMessage(uploadMsg);
//        }
//
//        openImageChooserActivity();
//    }

    // For Android  >= 4.1, 4.4.4
//    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//        openFileChooser(uploadMsg, acceptType);
//    }

    // For Android  4.4,4.4.1,4.4.2  去除了openFileChooser

    // For Android >= 5.0
//    @Override
//    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//        if (mActivity instanceof BaseWebViewToolbarActivity) {
//            ((BaseWebViewToolbarActivity) mActivity).setUploadMessageAbove5(filePathCallback);
//        } else if (mActivity instanceof MainActivity_) {
//            ((MainActivity_) mActivity).setUploadMessageAbove5(filePathCallback);
//        }
//        openImageChooserActivity();
//        return true;
//    }

    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
        super.onGeolocationPermissionsShowPrompt(origin, callback);
    }
}
